import {useEffect, useState} from 'react';
import React from 'react';
import {Image, View, AnimatableNumericValue, Text} from 'react-native';

type TokenLogoProp = {
  tokenName: string;
  logoUri?: string;
  size: number;
  backgroundColor?: string;
  textColor?: string;
  textFontSize?: number;
  borderRadius?: AnimatableNumericValue | string | undefined;
};

export function TokenLogo({
  tokenName,
  logoUri,
  size,
  backgroundColor,
  textColor,
  textFontSize,
  borderRadius,
}: Readonly<TokenLogoProp>) {
  const [imageError, setImageError] = useState<boolean>();
  useEffect(() => {
    setImageError(false);
  }, [logoUri]);

  const parseTokenName4Ui = () => {
    return tokenName.substring(0, 2);
  };

  return (
    <>
      {!imageError ? (
        <View>
          <Image
            onLoad={() => {
              setImageError(false);
            }}
            onError={() => {
              setImageError(true);
            }}
            source={{uri: logoUri}}
            style={{borderRadius: borderRadius, width: size, height: size}}
          />
        </View>
      ) : (
        <View
          style={{
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: backgroundColor ?? '#ccc',
            borderRadius: borderRadius,
            width: size,
            height: size,
          }}>
          <Text
            style={{
              color: textColor ?? '#fff',
              fontSize: textFontSize ?? 16,
              fontWeight: 'bold',
            }}>
            {parseTokenName4Ui()}
          </Text>
        </View>
      )}
    </>
  );
}
